﻿using Dapper;
using MySql.Data.MySqlClient;
using System;
using System.Collections.Generic;
using System.Data.Common;
using System.Text;

namespace _011_Dapper_mysql_study
{
    public class DapperHelper
    {
        static readonly string connectionStr = "Database=testdb;Data Source=192.168.16.106;User Id=root;Password=123456;CharSet=utf8;port=3306";

        static DbConnection dbConnection;
        public static DbConnection Connection
        {
            get
            {
                if (dbConnection == null)
                {
                    dbConnection = new MySqlConnection(connectionStr);
                    dbConnection.Open();
                }
                else if (dbConnection.State == System.Data.ConnectionState.Closed)
                {
                    dbConnection.Open();
                }
                return dbConnection;
            }
        }

        public static List<T> SelectObj<T>(string sql)
        {
            return Connection.Query<T>(sql).AsList();
        }

        public static int InsertObj<T>(string sql, T obj)
        {
            return Connection.Execute(sql, obj);
        }

        public static List<T> SelectObj<T, T2>(string sql)
        {
            return Connection.Query<T, T2, T>(sql, (g, r) =>
             {
                 T res = g;
                 foreach (var item in g.GetType().GetProperties())
                 {
                     if(item.PropertyType == typeof(T2))
                     {
                         item.SetValue(res, r);
                     }
                 }
                 return res;
             }).AsList();
        }
    }
}
